package com.avengers.core;

import com.jfinal.captcha.Captcha;
import com.jfinal.captcha.CaptchaManager;
import com.jfinal.captcha.ICaptchaCache;
import com.jfinal.core.Controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.xml.validation.Validator;

/**
 * @author yu.wang
 * @since 2019/6/18 11:47 AM
 **/
public abstract class AbstractBaseValidator extends Validator {
    private static final Logger logger = LoggerFactory.getLogger(AbstractBaseValidator.class);

    /**
     * 图形验证码key
     */
    protected static final String CAPTCHA_NAME = "_jfinal_captcha";


    /**
     * 验证图形验证码，不清除
     *
     * @param captcha
     * @return
     */
    public static boolean validateCaptcha(Controller c, String captcha) {
        String captchaKey = c.getCookie(CAPTCHA_NAME);
        return validate(captchaKey, captcha);
    }

    public static boolean validate(String captchaKey, String userInputString) {
        ICaptchaCache captchaCache = CaptchaManager.me().getCaptchaCache();
        Captcha captcha = captchaCache.get(captchaKey);
        return captcha != null && captcha.notExpired() && captcha.getValue().equalsIgnoreCase(userInputString);
    }

}
